package simple; /**
 * @projectName study-note
 * @package PACKAGE_NAME
 * @className PACKAGE_NAME.LengthOfLastWord
 */

/**
 * LengthOfLastWord
 * @description 最后一个单词的长度
 * @author answer_wx
 * @date 2022/7/3 23:22
 * @version 1.0
 */
public class LengthOfLastWord {
    public static int lengthOfLastWord(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        if (n <= 1) {
            return n;
        }
        int length = 0;
        for (int i = n - 1; i >= 0; i--) {
            if (' ' != chars[i]) {
                length++;
            }
            if ((' ' == chars[i] || i == 0) && length != 0) {
                return length;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        String s = "a ";
        System.out.println(lengthOfLastWord(s));
    }
}